package thread.visible;

/**
 * @author liweimin
 * @date 2021/4/27 11:00
 * @since
 */
public class VisibleTest {

    public static void main(String[] args) {
        MyTask task = new MyTask();
        new Thread(task).start();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        task.cancel();
    }

    static class MyTask implements Runnable {
        private boolean toCancel = false;

        @Override
        public void run() {
            while (!toCancel) {
                doSomething();
            }
            if (toCancel) {
                System.out.println("任务被取消-------");
            } else {
                System.out.println("任务已完成-------");
            }
        }

        public void cancel() {
            toCancel = true;
            System.out.println("收到取消线程的消息");
        }

        private void doSomething() {
            System.out.println("doSomething");

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
